<template>
  <div class="send-coin">
    <!-- 查询区域 -->
    <el-card class="mb search-card">
      <el-form :model="searchParams" inline>
        <el-form-item label="用户编号" style="margin-right: 20px;">
          <el-input
            v-model="searchParams.userNo"
            placeholder="请输入用户编号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="操作员" style="margin-right: 20px;">
          <el-input
            v-model="searchParams.operator"
            placeholder="请输入操作员"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset" style="margin-right: 10px;">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAddSendCoin" v-permission="'addCoin_btn'">
            <el-icon><Plus /></el-icon>
            赠送金币
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        :fit="true"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" min-width="60" align="center" />
        <el-table-column label="用户编号" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.ext?.userNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="金币数量" min-width="120" align="center">
          <template #default="{ row }">
            <span class="coin-amount">{{ formatNumber(row.amount || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作前余额" min-width="120" align="center">
          <template #default="{ row }">
            <span class="balance">{{ formatNumber(row.balanceBefore || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作后余额" min-width="120" align="center">
          <template #default="{ row }">
            <span class="balance">{{ formatNumber(row.balance || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="交易类型" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.transactionType === 'ADMIN_RECHARGE' ? 'success' : 'info'" size="small">
              {{ getTransactionTypeText(row.transactionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易ID" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.transactionId || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作员" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.ext?.operator || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.remark || '-' }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination 
        class="pagination-center pagination-spacing"
        v-model:current-page="pagination.page" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="totals" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
        background
      />
    </el-card>

    <!-- 赠送金币弹窗 -->
    <el-dialog
      v-model="sendCoinDialogVisible"
      title="修改金币"
      width="580px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="send-coin-dialog"
    >
      <el-form
        ref="sendCoinFormRef"
        :model="sendCoinForm"
        :rules="sendCoinRules"
        label-width="100px"
      >
        <el-form-item label="业务类型:" prop="businessType">
          <el-select
            v-model="sendCoinForm.businessType"
            placeholder="请选择业务类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in businessTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户编号:" prop="userNo">
          <el-input
            v-model="sendCoinForm.userNo"
            placeholder="请输入用户编号"
            clearable
            @blur="handleValidateUserNo"
          />
          <div v-if="userNoValidating" class="validating-text">正在验证用户...</div>
          <div v-if="userNoValidationError" class="error-text">{{ userNoValidationError }}</div>
          <div v-if="userNoValidationSuccess" class="success-text">用户验证成功</div>
        </el-form-item>
        
        <el-form-item label="变化金额:" prop="amount">
          <el-input-number
            v-model="sendCoinForm.amount"
            :min="1"
            :max="10000000"
            :precision="0"
            placeholder="请输入变化金额"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="理由:" prop="reason">
          <el-input
            v-model="sendCoinForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入理由"
            :maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelSendCoin">取消</el-button>
          <el-button
            type="primary"
            :loading="sendCoinLoading"
            @click="handleConfirmSendCoin"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus, User } from '@element-plus/icons-vue'
import { getAdminAdjustRecordPageApi, adjustCoinApi, type CoinTransactionRecordDto, type AdminAdjustRecordReq, type AdjustCoinReq } from '@/api/wallet'
import { checkUserNoApi } from '@/api/user'

// 搜索参数
const searchParams = reactive({
  userNo: '',
  operator: '',
  pageIndex: 1,
  pageSize: 10
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const totals = ref(0)
const pagination = reactive({
  page: 1,
  pageSize: 10
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const requestParams: AdminAdjustRecordReq = {
      userNo: searchParams.userNo || undefined,
      operator: searchParams.operator || undefined,
      pageIndex: pagination.page,
      pageSize: pagination.pageSize
    }
    
    // 过滤空值
    const filteredParams = Object.fromEntries(
      Object.entries(requestParams).filter(([_, value]) => {
        return value !== '' && value !== null && value !== undefined
      })
    )
    
    const { data } = await getAdminAdjustRecordPageApi(filteredParams)
    tableData.value = data.list || []
    totals.value = data.total || 0
  } catch (error) {
    console.error('加载赠送金币列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置方法
const handleReset = () => {
  Object.assign(searchParams, {
    userNo: '',
    operator: '',
    pageIndex: 1,
    pageSize: 10
  })
  pagination.page = 1
  pagination.pageSize = 10
  // 重置后重新加载数据
  loadData()
}

// 分页方法
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num === 0) return '0'
  return num.toLocaleString()
}

// 获取交易类型文本
const getTransactionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'ADMIN_RECHARGE': '管理员充值'
  }
  return typeMap[type] || type
}

// 赠送金币弹窗相关数据
const sendCoinDialogVisible = ref(false)
const sendCoinLoading = ref(false)
const sendCoinFormRef = ref()
const sendCoinForm = reactive({
  businessType: 'increase', // 业务类型：increase-增加，decrease-减少
  userNo: '', // 用户编号
  amount: 1000, // 变化金额
  reason: '' // 理由
})

// 用户验证相关状态
const userNoValidating = ref(false)
const userNoValidationError = ref('')
const userNoValidationSuccess = ref(false)

// 业务类型选项
const businessTypeOptions = [
  { label: '增加充值金币', value: 'increase' },
  { label: '减少充值金币', value: 'decrease' }
]

// 表单验证规则
const sendCoinRules = {
  userNo: [
    { required: true, message: '请输入用户编号', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value && userNoValidationError.value) {
          callback(new Error('用户不存在'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  amount: [
    { required: true, message: '请输入变化金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '金额必须大于0', trigger: 'blur' },
    { type: 'number', max: 10000000, message: '金额不能超过10,000,000', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入理由', trigger: 'blur' },
    { max: 20, message: '理由不能超过20个字符', trigger: 'blur' }
  ]
}

// 赠送金币
const handleAddSendCoin = () => {
  sendCoinDialogVisible.value = true
  // 重置表单
  sendCoinForm.userNo = ''
  sendCoinForm.amount = 1000
  sendCoinForm.reason = ''
  sendCoinForm.businessType = 'increase'
  // 重置验证状态
  userNoValidating.value = false
  userNoValidationError.value = ''
  userNoValidationSuccess.value = false
}

// 确认赠送金币
const handleConfirmSendCoin = async () => {
  if (!sendCoinFormRef.value) return
  
  try {
    await sendCoinFormRef.value.validate()
    
    // 检查用户验证状态
    if (sendCoinForm.userNo && userNoValidationError.value) {
      ElMessage.error('请先验证用户编号')
      return
    }
    
    sendCoinLoading.value = true
    
    // 构建请求参数
    const requestData: AdjustCoinReq = {
      userNo: sendCoinForm.userNo,
      coin: sendCoinForm.businessType === 'increase' ? sendCoinForm.amount : -sendCoinForm.amount,
      remark: sendCoinForm.reason
    }
    
    // 调用后端API
    await adjustCoinApi(requestData)
    
    ElMessage.success('操作成功')
    sendCoinDialogVisible.value = false
    // 重新加载数据
    loadData()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    sendCoinLoading.value = false
  }
}

// 验证用户编号
const handleValidateUserNo = async () => {
  if (!sendCoinForm.userNo) {
    userNoValidationError.value = ''
    userNoValidationSuccess.value = false
    return
  }
  
  userNoValidating.value = true
  userNoValidationError.value = ''
  userNoValidationSuccess.value = false
  
  try {
    const { data } = await checkUserNoApi(sendCoinForm.userNo)
    if (data) {
      userNoValidationSuccess.value = true
      userNoValidationError.value = ''
    } else {
      userNoValidationError.value = '用户不存在'
      userNoValidationSuccess.value = false
    }
  } catch (error) {
    console.error('验证用户失败:', error)
    userNoValidationError.value = '用户不存在或验证失败'
    userNoValidationSuccess.value = false
  } finally {
    userNoValidating.value = false
  }
}

// 取消赠送金币
const handleCancelSendCoin = () => {
  sendCoinDialogVisible.value = false
  // 重置验证状态
  userNoValidating.value = false
  userNoValidationError.value = ''
  userNoValidationSuccess.value = false
}

onMounted(() => {
  loadData()
})
</script>

<style lang="less" scoped>
.send-coin {
  font-size: 16px;
  
  .mb {
    margin-bottom: 20px;
  }
  
  .mt {
    margin-top: 20px;
  }
  
  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .pagination-spacing {
    margin-top: 30px;
    margin-bottom: 20px;
  }

  .table-card {
    margin-top: 20px;
  }

  .search-card {
    padding: 20px;
  }

  // 表格字体大小设置
  :deep(.el-table) {
    font-size: 16px;
    
    .el-table__header {
      th {
        font-size: 17px;
        font-weight: 600;
        color: #303133;
        padding: 16px 0;
        height: 60px;
      }
    }
    
    .el-table__body {
      td {
        font-size: 16px;
        color: #606266;
        padding: 20px 0;
        height: 70px;
      }
    }
  }

  // 表格内容区域的字体大小
  :deep(.el-table__cell) {
    font-size: 16px;
  }

  // 用户信息样式
  .user-info {
    .user-name {
      font-weight: 500;
      margin-bottom: 4px;
      font-size: 17px;
    }
    
    .user-id {
      font-size: 15px;
      color: #909399;
    }
  }

  // 金币数量样式
  .coin-amount {
    color: #e6a23c;
    font-weight: 500;
    font-size: 17px;
  }

  // 余额样式
  .balance {
    color: #409eff;
    font-weight: 500;
    font-size: 17px;
  }

  // 标签样式调整
  :deep(.el-tag) {
    font-size: 15px;
  }

  // 验证状态样式
  .validating-text {
    color: #409eff;
    font-size: 13px;
    margin-top: 6px;
  }

  .error-text {
    color: #f56c6c;
    font-size: 13px;
    margin-top: 6px;
  }

  .success-text {
    color: #67c23a;
    font-size: 13px;
    margin-top: 6px;
  }

  // 赠送金币弹窗样式
  :deep(.send-coin-dialog) {
    .el-dialog {
      border-radius: 16px !important;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15) !important;
      overflow: hidden;
      
      .el-dialog__header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 24px 30px 20px !important;
        margin: 0 !important;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 1px;
          background: rgba(255, 255, 255, 0.2);
        }
        
        .el-dialog__title {
          font-size: 20px !important;
          font-weight: 600 !important;
          color: white !important;
        }
        
        .el-dialog__headerbtn {
          top: 24px !important;
          right: 30px !important;
          
          .el-dialog__close {
            font-size: 20px !important;
            color: rgba(255, 255, 255, 0.8) !important;
            
            &:hover {
              color: white !important;
              transform: scale(1.1);
            }
          }
        }
      }
      
      .el-dialog__body {
        padding: 30px !important;
        background: #fafbfc;
        
        .el-form {
          .el-form-item {
            margin-bottom: 24px !important;
            
            .el-form-item__label {
              font-weight: 600 !important;
              color: #2c3e50 !important;
              font-size: 15px !important;
              line-height: 1.4;
            }
            
            .el-form-item__content {
              .el-select,
              .el-input,
              .el-input-number {
                .el-input__wrapper {
                  border-radius: 12px !important;
                  border: 2px solid #e1e8ed !important;
                  background: white !important;
                  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04) !important;
                  transition: all 0.3s ease !important;
                  
                  &:hover {
                    border-color: #409eff !important;
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15) !important;
                  }
                  
                  &.is-focus {
                    border-color: #409eff !important;
                    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1) !important;
                  }
                  
                  .el-input__inner {
                    font-size: 15px !important;
                    color: #2c3e50 !important;
                  }
                }
              }
              
              .el-textarea {
                .el-textarea__inner {
                  border-radius: 12px !important;
                  border: 2px solid #e1e8ed !important;
                  background: white !important;
                  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04) !important;
                  transition: all 0.3s ease !important;
                  font-size: 15px !important;
                  color: #2c3e50 !important;
                  resize: vertical;
                  
                  &:hover {
                    border-color: #409eff !important;
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15) !important;
                  }
                  
                  &:focus {
                    border-color: #409eff !important;
                    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1) !important;
                  }
                }
              }
            }
            
            &.is-error {
              .el-form-item__content {
                .el-input__wrapper,
                .el-textarea__inner {
                  border-color: #f56c6c !important;
                  box-shadow: 0 0 0 3px rgba(245, 108, 108, 0.1) !important;
                }
              }
              
              .el-form-item__error {
                color: #f56c6c !important;
                font-size: 13px !important;
                margin-top: 6px !important;
              }
            }
          }
        }
      }
      
      .el-dialog__footer {
        padding: 20px 30px 30px !important;
        background: white !important;
        margin: 0 !important;
        border-top: 1px solid #e1e8ed;
        
        .dialog-footer {
          display: flex !important;
          justify-content: flex-end !important;
          gap: 16px !important;
          
          .el-button {
            border-radius: 12px !important;
            font-weight: 600 !important;
            font-size: 15px !important;
            padding: 12px 24px !important;
            transition: all 0.3s ease !important;
            min-width: 80px;
            
            &.el-button--default {
              border: 2px solid #e1e8ed !important;
              color: #606266 !important;
              background: white !important;
              
              &:hover {
                border-color: #409eff !important;
                color: #409eff !important;
                background: rgba(64, 158, 255, 0.05) !important;
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2) !important;
              }
            }
            
            &.el-button--primary {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
              border: none !important;
              color: white !important;
              
              &:hover {
                background: linear-gradient(135deg, #7c8ff0 0%, #8a5bb8 100%) !important;
                transform: translateY(-1px);
                box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4) !important;
              }
              
              &:active {
                transform: translateY(0);
              }
            }
          }
        }
      }
    }
  }
}
</style>